import { callCloudFun } from "../utiles/callCloudFun"
import { getAutoAcceptOrder, putAdminOrderDetailUpdateApi } from "./admin"
const db = wx.cloud.database()
const _ = db.command

// 获取当前桌号的流水单id
export const getUserUserTurnoverIdApi = async (place : number) => {
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		if (!place) {
			throw new Error('没有桌号，请重新登录')
		}
		const { data: turnovers } = await db.collection('turnover').field({ userId: true, number: true }).where(_.and([{ status: _.lt(2) }, { place: _.eq(place) }])).get()
		if (turnovers.length > 1) {
			throw new Error('当前桌有异常，有多个流水单')
		}
		wx.hideLoading()
		if (turnovers.length === 0) {
			return []
		} else {
			return [turnovers[0]._id, turnovers[0].userId, turnovers[0].number]
		}
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message, icon: 'none' })
		throw error
	}
}

// 创建新流水单
export const postUserUserCreateTurnoverApi = async (turnover : any) => {
	try {
		wx.showLoading({ title: '请稍候...', mask: true })
		if (!turnover.place || !turnover.people || !turnover.userId) {
			throw new Error('参数不全，请重试')
		}
		const { data: turnovers } = await db.collection('turnover').field({ userId: true, number: true }).where(_.and([{ status: _.lt(2) }, { place: _.eq(turnover.place) }])).get()
		if (turnovers.length !== 0) {
			return [turnovers[0]._id, turnovers[0].userId, turnovers[0].number]
		}
		turnover.number = Date.now() + '-' + ('000' + turnover.place).slice(-3)
		turnover.createTime = db.serverDate()
		turnover.completeTime = db.serverDate()
		turnover.status = 0
		const { _id: turnoverId } = await db.collection('turnover').add({ data: turnover })
		const { data: [dish] } = await db.collection('dish').where({ name: '餐具' }).get()
		const autoAccept = await getAutoAcceptOrder()
		const { _id: orderId } = await db.collection('orders').add({
			data: {
				turnoverId,
				orderTime: db.serverDate(),
				number: Date.now().toString(),
				userId: turnover.userId,
				amount: dish.price * turnover.people,
				status: autoAccept === '0' ? 1 : 2,
				completeTime: null,
				statementId: null,
				remark: '按人数配餐具',
				cancelReason: null,
				cancelTime: null
			}
		})
		await db.collection('order_detail').add({
			data: {
				name: dish.name,
				image: dish.image,
				dishId: dish._id,
				number: turnover.people,
				amount: dish.price,
				orderId,
				place: turnover.place,
				status: 2,
				setmealId: null,
				dishFlavor: null,
				chefId: null,
				waiterId: null,
				completeTime: db.serverDate()
			}
		})
		return [turnoverId, turnover.userId, turnover.number]
	} catch (error) {
		throw error
	} finally {
		wx.hideLoading()
	}
}

// 按流水id查询购物车列表
export const getUserShoppingCartListApi = async (turnoverId : number = null) => {
	try {
		const { data: res } = await db.collection('shopping_cart').where({ turnoverId }).get()
		return res
	} catch (error) {
		throw error
	}
}

// 增加一个购物车菜品
export const postUserShoppingCartAddApi = async (shoppingCart : any) => {
	try {
		wx.showLoading({ title: '请稍候...', mask: true })
		// 1. 参数校验
		if (!shoppingCart?.turnoverId) {
			throw new Error('缺少必要参数: turnoverId')
		}

		// 2. 构建查询条件
		const conditions : any = [{ turnoverId: _.eq(shoppingCart.turnoverId) }]

		if (shoppingCart.dishId) {
			conditions.push({ dishId: _.eq(shoppingCart.dishId) })
		}
		if (shoppingCart.dishFlavor) {
			conditions.push({ dishFlavor: _.eq(shoppingCart.dishFlavor) })
		}
		if (shoppingCart.setmealId) {
			conditions.push({ setmealId: _.eq(shoppingCart.setmealId) })
		}

		// 3. 查询是否已存在购物车项
		const { data: existingItems } = await db.collection('shopping_cart')
			.where(_.and(conditions))
			.get()

		// 4. 如果已存在则更新数量，否则新增
		if (existingItems.length > 0) {
			await db.collection('shopping_cart')
				.doc(existingItems[0]._id)
				.update({
					data: {
						number: _.inc(1), // 数量+1
					}
				})
		} else {
			// 5. 新增购物车项
			const newItem = {
				...shoppingCart,
				number: 1, // 默认数量1
				createTime: db.serverDate(),
			}
			await db.collection('shopping_cart').add({
				data: newItem
			})
		}
		await wx.hideLoading()
		return
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({
			title: error.message || '添加购物车失败',
			icon: 'none'
		})
		throw error
	}
}

// 按流水id查询订单列表(包括订单详情)
export const getUserOrderTurnoverIdApi = async (turnoverId : number) => {
	const orderList = []
	for (let i = 0; ; i += 20) {
		const { data: list } = await db.collection('orders').where({ turnoverId: _.eq(turnoverId), status: _.lt(4), statementId: _.eq(null) }).orderBy('orderTime', 'asc').skip(i).limit(20).get()
		if (list.length === 0) break
		orderList.push(...list)
		if (list.length < 20) break
	}

	if (orderList && orderList.length > 0) {
		const orderIds = orderList.map(item => item._id)
		const orderDetailList = []
		for (let i = 0; ; i += 20) {
			const { data: list } = await db.collection('order_detail').where(_.and([{ orderId: _.in(orderIds) }, { status: _.lt(4) }])).skip(i).limit(20).get()
			if (list.length === 0) break
			orderDetailList.push(...list)
			if (list.length < 20) break
		}
		orderList.forEach(item => {
			item.orderDetailList = orderDetailList.filter(e => e.orderId === item._id)
		})
	}
	return orderList
}

// 修改购物车数量和选中状态
export const putUserShoppingCartUpdateApi = async (data : any) => {
	try {
		let res : any;
		wx.showLoading({ title: '请稍候...', mask: true })
		if (data.number === 0) {
			res = await db.collection('shopping_cart').doc(data.id).remove()
		} else {
			let condition = {}
			if (data.selected === 0 || data.selected === 1) {
				condition = { selected: data.selected }
			} else {
				condition = { number: data.number }
			}
			res = await db.collection('shopping_cart').doc(data.id).update({ data: condition })
		}
		wx.hideLoading()
		return res
	} catch (error) {
		wx.hideLoading()
		wx.showToast({ title: '操作失败', icon: 'none' })
		throw error
	}
}

// 修改购物车为全选或取消全选
export const putUserShoppingCartSelectAllApi = async (params : any) => {
	wx.showLoading({ title: '请稍候...', mask: true })
	const res = await Promise.all(params.ids.map((item : string) => db.collection('shopping_cart').doc(item).update({ data: { selected: params.selected } })))
	wx.hideLoading()
	return res
}

// // 取消订单（一个菜品）
// export const putUserOrderCancelApi = async (params : any) => {
// 	try {
// 		wx.showLoading({ title: '请稍候...', mask: true })
// 		const orderList = []
// 		// 查询当前流水单中的所有
// 		for (let i = 0; ; i += 20) {
// 			const { data: list } = await db.collection('orders').field({ _id: true }).where({ turnoverId: params.turnoverId, status: _.lt(3) }).skip(i).limit(20).get()
// 			if (list.length === 0) break
// 			orderList.push(...list)
// 			if (list.length < 20) break
// 		}
// 		if (orderList.length === 0) {
// 			throw new Error('当前菜品状态不可取消')
// 		}
// 		const orderIds = orderList.map(item => item._id)
// 		const { data: orderDetailList } = await db.collection('order_detail').field({ _id: true })
// 			.where(_.and([{ orderId: _.in(orderIds) }, { name: _.eq(params.name) }, { dishFlavor: _.eq(params.dishFlavor) }, { status: _.eq(0) }])).orderBy('completeTime', 'desc').get()
// 		const res = await putAdminOrderDetailUpdateApi({ id: orderDetailList[0]._id, status: 4 }, false)
// 		await wx.hideLoading()
// 		return res
// 	} catch (error) {
// 		await wx.hideLoading()
// 		wx.showToast({ title: error.message || '取消失败，请重试', icon: 'none' })
// 		throw error
// 	}
// }

// 下单
export const postUserOrderSubmitApi = async (params : any) => {
	const categoryNameWhite = ['酒水饮料', '餐具']
	try {
		const userId = wx.getStorageSync('userId')
		if (!userId) {
			wx.showToast({ title: '参数错误，请重新登录', icon: 'none' })
			wx.reLaunch({ url: 'pages/index/index' })
			return
		}
		wx.showLoading({ title: '请稍候...', mask: true })
		const { data: turnover } = await db.collection('turnover').doc(params.turnoverId).get()
		if (turnover.status === 2) {
			await callCloudFun('batchDel', { name: 'shopping_cart', where: { turnoverId: params.turnoverId } })
			throw new Error('该桌已清台，请重新扫码登录')
		}
		const dishIds = params.shoppingCartList.map((item : { dishId : any }) => item.dishId).filter((item : any) => item)
		const setmealIds = params.shoppingCartList.map((item : { setmealId : any }) => item.setmealId).filter((item : any) => item)
		let disableDishs = []
		let disableSetmeals = []
		if (dishIds.length !== 0) {
			({ data: disableDishs } = await db.collection('dish').field({ name: true, _id: false }).where(_.and([{ status: 0 }, { _id: _.in(dishIds) }])).get())
		}
		if (setmealIds !== 0) {
			({ data: disableSetmeals } = await db.collection('setmeal').field({ name: true, _id: false }).where(_.and([{ status: 0 }, { _id: _.in(setmealIds) }])).get())
		}
		let sellOutNames = []
		if (disableDishs.length > 0) {
			sellOutNames = [...disableDishs.map(item => item.name)]
		}
		if (disableSetmeals.length > 0) {
			sellOutNames = [...sellOutNames, ...disableSetmeals.map(item => item.name)]
		}
		if (sellOutNames.length > 0) {
			await callCloudFun('batchDel', { name: 'shopping_cart', where: { turnoverId: params.turnoverId, name: { $in: sellOutNames } } })
			return { sellOutList: [...new Set(sellOutNames)].join() }
		}
		const autoAccept = await getAutoAcceptOrder()
		const orders = {
			amount: params.amount,
			turnoverId: params.turnoverId,
			orderTime: db.serverDate(),
			number: Date.now().toString(),
			userId,
			status: autoAccept === '0' ? 1 : 2,
			statementId: null,
			completeTime: null,
			cancelTime: null,
			cancelReason: null,
			remark: null
		}
		const { _id: orderId } = await db.collection('orders').add({ data: orders })
		let allShoppingCarts = []
		for (let i = 0; ; i += 20) {
			const { data: list } = await db.collection('shopping_cart').where({ turnoverId: params.turnoverId }).skip(i).limit(20).get()
			if (list.length === 0) break
			allShoppingCarts.push(...list)
			if (list.length < 20) break
		}
		if (allShoppingCarts.length === 0) {
			throw new Error('购物车为空，请先添加')
		}
		for (let item of params.shoppingCartList) {
			// 先处理购物车中的数据
			const shoppingCarts = allShoppingCarts.filter(e => e.dishId == item.dishId && e.setmealId == item.setmealId && e.dishFlavor === item.dishFlavor)
			if (shoppingCarts.length !== 0 && item.number < shoppingCarts[0].number) {
				await db.collection('shopping_cart').doc(shoppingCarts[0]._id).update({ data: { number: shoppingCarts[0].number - item.number } })
			} else if (shoppingCarts.length !== 0) {
				await db.collection('shopping_cart').doc(shoppingCarts[0]._id).remove()
			}
			// 添加订单详情表数据
			const orderDetail : any = {
				name: item.name,
				image: item.image,
				dishId: item.dishId,
				setmealId: item.setmealId,
				dishFlavor: item.dishFlavor,
				amount: item.amount,
				orderId,
				place: turnover.place,
				completeTime: db.serverDate(),
				chefId: null,
				waiterId: null
			}
			if (categoryNameWhite.includes(item.categoryName)) {
				orderDetail.status = 2
				orderDetail.number = item.number
				await db.collection('order_detail').add({ data: orderDetail })
			} else {
				orderDetail.status = 0
				orderDetail.number = 1
				await Promise.all(Array.from({ length: item.number }).map(() => db.collection('order_detail').add({ data: orderDetail })))
			}
		}
		await wx.hideLoading()
		return {}
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || '下单失败', icon: 'none' })
		throw error
	}
}

// 查看店铺营业状态
export const getUserShopStatusApi = async () => {
	const { data: [{ createUser: res }] } = await db.collection('employee').field({ createUser: true, _id: false }).where({ username: 'admin' }).get()
	return res
}

// 生成结账单
export const postUserUserStatementSubmitApi = async (params : any) => {
	let step = 0
	let statementId : DB.DocumentId;
	const { orderIds, ...addData } = params
	const unPayorderList = []
	try {
		wx.showLoading({ title: '结账中...', mask: true })
		for (let i = 0; ; i += 20) {
			const { data: list } = await db.collection('orders').field({ _id: true }).where({ turnoverId: params.turnoverId, status: _.lt(4), statementId: null }).skip(i).limit(20).get()
			if (list.length === 0) break
			unPayorderList.push(...list)
			if (list.length < 20) break
		}
		if (orderIds.length !== unPayorderList.length || !unPayorderList.every(item => orderIds.includes(item._id))) {
			throw new Error('数据发生变化，请刷新后再试')
		}
		addData.createTime = db.serverDate();
		console.log("添加结算单：", addData);
		({ _id: statementId } = await db.collection('statement').add({ data: addData }))
		step = 1
		// 填充订单记录的statementId
		await Promise.all(orderIds.map((item : string | number) => db.collection('orders').doc(item).update({ data: { statementId } })))
		step = 2
		// 修改流水单状态
		await db.collection('turnover').doc(params.turnoverId).update({ data: { status: 1 } })
		wx.hideLoading()
	} catch (error) {
		if (step >= 1) {
			db.collection('statement').doc(statementId).remove()
			Promise.all(orderIds.map((item : string | number) => db.collection('orders').doc(item).update({ data: { statementId: null } })))
		}
		await wx.hideLoading()
		wx.showToast({ title: '出现异常，请重新操作', icon: 'none' })
		throw error
	}
}